/*
  EOMono
  Copyright 2007, Adam Tauno Williams (Whitemice Consulting)
  License: LGPLv2  < http://www.gnu.org/licenses/lgpl-2.1.html >
 */
using System;
using System.Text;

namespace Whitemice.EOMono
{
  [EOCommandAttribute("SQLSet", 1, "Update the provided record")]
  public class EOSQLSetCommand : EOSQLCommand, IEOCommand
  {
    protected IEORecord  record = null;
    
    public EOSQLSetCommand(IEOConnection _connection, string _entity) :
      base(_connection, _entity)
    {
    } // end ctor
    
    [EOArguementAttribute("record", "")]
    public IEORecord Record
    {
      set { record = value; }
      get { return record; }
    } // end Record
    
    protected override void Execute()
    {
      StringBuilder  sql   = new StringBuilder();
      bool           first = true;
      string         format;

      if (Record == null)            
        throw new Exception("Set command with no record");
        
      if (Record.Entity.ReadOnly)
        throw new Exception("Set command on read-only entity.");        
        
      if (!(Record.IsUpdateComplete))
        throw new Exception("Set command with incomplete record");
      
      /* build SQL for UPDATE statement */
      first = true;
      sql.AppendFormat("UPDATE {0} SET ", Entity.InternalName);
      foreach(EOFieldDef field in Record.Fields)
      {
        if (field.Kind.ToLower() != "serial")
        {
          if (first)
          {
            format = @"{0} = {1}";
            first = false;
          } else format = @",{0} = {1}";
          sql.AppendFormat(format, field.Name, Record.SQLValue(field.Name));
        } 
      } // end build-set-clause
      sql.Append(" WHERE ");
      first = true;
      foreach(string field in Entity.PrimaryKeys)
      {
        if (Record[field].HasValue)
        {
          if (first)
          {
            format = @" {0} = {1}";
            first = false;
          } else format = @" AND {0} = {1}";
          sql.AppendFormat(format, field, Record.SQLValue(field));
        } else throw new Exception("Primary key value cannot be NULL");
      } // end build-where-clause
      command.CommandText = sql.ToString();
      EOManager.Log.DebugFormat("SQL:{0}", sql.ToString());
      command.ExecuteNonQuery();
      results = connection.Run(string.Format("{0}:SQLFetch", Record.Entity.Name),
                               "qualifier", PrimaryKeyQualifier(Record)); 
    } // end Execute
  } // end class
}
